package com.zHan.sky.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zHan.sky.common.result.Result;
import com.zHan.sky.dto.DishDto;
import com.zHan.sky.entity.Category;
import com.zHan.sky.entity.Dish;
import com.zHan.sky.entity.DishFlavor;
import com.zHan.sky.service.CategoryService;
import com.zHan.sky.service.DishFlavorService;
import com.zHan.sky.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController("adminDishController")
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关接口")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    @ApiOperation(value = "新增菜品")
    public Result<String> save(@RequestBody DishDto dishDto) {

        //清理redis缓存数据--> 精确清理
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);

        dishService.saveWithFlavor(dishDto);
        return Result.success("菜品添加成功");
    }

    /**
     * 菜品信息分页查询
     *
     * @param page
     * @param pageSize
     * @param dish
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "菜品信息分页查询")
    public Result<Page> page(int page, int pageSize, Dish dish) {
        //分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        String name = dish.getName();
        Long id = dish.getCategoryId();
        Integer status = dish.getStatus();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name)
                .eq(id !=null,Dish::getCategoryId, id)
                .eq(status !=null,Dish::getStatus, status);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> dishDtoList= records.stream().map((item)->{
            //创建一个dishDto对象
            DishDto dishDto=new DishDto();

            //将dish对象拷贝给dishDto对象
            BeanUtils.copyProperties(item,dishDto);

            //获得分类id
            Long categoryId = item.getCategoryId();
            //根据分类id得到分类对象
            Category category = categoryService.getById(categoryId);
            //获得对应的分类名称
            String categoryName = category.getName();
            //将名称赋值给dishDto
            dishDto.setCategoryName(categoryName);

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(dishDtoList);

        return Result.success(dishDtoPage);
    }

    /**
     * 根据id查询单个菜品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询单个菜品信息")
    public Result<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return Result.success(dishDto);
    }

    /**
     * 修改菜品信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    @ApiOperation(value = "修改菜品信息")
    public Result<String> update(@RequestBody DishDto dishDto) {

        //清理redis缓存数据--> 精确清理
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);

        dishService.updateWithFlavor(dishDto);
        return Result.success("修改菜品信息成功");
    }

    /**
     * 启售停售菜品信息
     *
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation(value = "启售停售菜品信息")
    public Result<String> status(@PathVariable Integer status, @RequestParam Long id) {
        //条件构造器对象
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getId, id);
        Dish dish = dishService.getOne(queryWrapper);

        //执行方法
        dish.setStatus(status);
        dishService.updateById(dish);

        return Result.success("停售菜品成功");
    }

    /**
     * 批量删除菜品信息
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @ApiOperation(value = "批量删除菜品信息")
    public Result<String> delete(@RequestParam List<Long> ids) {
        dishService.deleteWithFlavor(ids);
        return Result.success("删除成功");
    }

    /**
     * 根据条件查询菜品数据
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value = "根据条件查询菜品数据")
    public Result<List<DishDto>> list(Dish dish) {

        List<DishDto> dishDtoList = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //在redis中查询有没有数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList != null) {
            //若存在，直接获取
            return Result.success(dishDtoList);
        }

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //过滤条件
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //只查询启售的菜品，status=1
        queryWrapper.eq(Dish::getStatus, 1);
        //排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行方法
        List<Dish> dishList = dishService.list(queryWrapper);

        dishDtoList = dishList.stream().map((item) -> {
            //创建dishDto
            DishDto dishDto = new DishDto();
            //对象拷贝
            BeanUtils.copyProperties(item, dishDto);
            //获得categoryId
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //获得菜品id
            Long id = item.getId();
            //根据菜品id查到对应口味
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, id);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);

            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        //若不存在，添加数据到redis
        redisTemplate.opsForValue().set(key, dishDtoList, 1, TimeUnit.HOURS);


        return Result.success(dishDtoList);
    }

}
